﻿using Futajma.MigrationStudio.DataDefinition;
using Futajma.MigrationStudio.SharePointPersistance;
using Futajma.MigrationStudio.GenericPersistance;
using Futajma.MigrationStudio.GenericPersistance.Data;
using Microsoft.SharePoint.Client;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Principal;
using System.Text;
using System.Windows.Forms;
using System.Xml;
using System.Xml.Serialization;
using Futajma.MigrationStudio.SharePointPersistence;

namespace Futajma.MigrationStudio.SharePointPersistance
{
    public class SharePoint2010ProjectPersistence : ProjectPersistence
    {
        
        #region Private

        void SaveFileAsZipToFolder(Stream fileStream, string fileName, int folderId, string listTitle)
        {
            var progressWrapper = new ProgressStreamWrapper(fileStream);

            SendProgressInit(fileStream.Length / 1000, "Compress file");
            progressWrapper.PositionChanged += progressWrapper_PositionChanged;

            MemoryStream ms = CreateZipStream(fileStream, fileName + ".xml");

            SendProgressInit(ms.Length / 1000, "Upload file to dashboard");

            progressWrapper = new ProgressStreamWrapper(ms);
            progressWrapper.PositionChanged += progressWrapper_PositionChanged;

            ExtendedClientContext clientContext = new ExtendedClientContext(Settings.MigrationPortalUrl);

            string url = "";
            var item = Utils.GetFileFromFolder(clientContext, folderId, fileName + ".zip", listTitle);

            if (item == null)
            {
                var folder = Utils.GetFolder(clientContext, folderId, listTitle);
                url = string.Format("{0}/{1}", (string)folder["FileRef"], fileName + ".zip");
            }
            else
            {
                url = (string)item["FileRef"];
            }

            Microsoft.SharePoint.Client.File.SaveBinaryDirect(clientContext, url, progressWrapper, true);
        }

        void progressWrapper_PositionChanged(object sender, long newPosition, long length)
        {
            SendProgressUpdate(newPosition / 1000);
        }

        #endregion

        public override void Save(object sendTo, System.Windows.Forms.TreeView sourceTreeView, System.Windows.Forms.TreeView targetTreeView, ProjectData projectData)
        {
            int folderId = (int)sendTo;
            //MemoryStream memStr = new MemoryStream();

            using (MemoryStream memStr = new MemoryStream())
            {
                SaveData(memStr, sourceTreeView, targetTreeView, projectData);
                memStr.Position = 0;

                SharePoint2010Persistence pers = new SharePoint2010Persistence();
                //var isAdmin = pers.EnsureUserInGroup(int.Parse(Settings.MigrationTeamGroupId), WindowsIdentity.GetCurrent().Name);
                var isAdmin = pers.EnsureUserInGroup(int.Parse(Settings.MigrationTeamGroupId), CredentialManager.ToString());

                if (!Utils.CheckIfItemIsValid(folderId, Settings.MigrationListTitle, isAdmin ? Settings.MigrationWriteableQueryAsAdmin : Settings.MigrationWriteableQuery))
                {
                    throw new NotSupportedException("The record is already closed for manipulation. Please contact migration support");
                }

                SaveFileAsZipToFolder(memStr, Settings.ProjectPersistenceDataItemTitle, folderId, Settings.MigrationListTitle);

                if (Settings.Statistics_EnableStatisticRecording.ToLower() == "true")
                {
                    //var complexity = new DataComplexityCalculation();

                    var statistic = new MigrationStatistic();

                    statistic.MigrationPlannedSourceElements = DataComplexityCalculation.CountItemWithOutFolders(sourceTreeView);
                    statistic.MigrationActualsSourceElements = DataComplexityCalculation.CountItemWithOutFolders(targetTreeView);
                    statistic.MigrationPlannedSourceSize = DataComplexityCalculation.CountSizeWithOutFolders(sourceTreeView);
                    statistic.MigrationActualsSourceSize = DataComplexityCalculation.CountSizeWithOutFolders(targetTreeView);

                    var statisitcPersitence = new SharePoint2010MigrationStatistic();
                    statisitcPersitence.SaveStatistics(folderId, statistic);

                }

            }
            SendProgressUpdateDone();
        }

        public override void Load(object readFrom, System.Windows.Forms.TreeView sourceTreeView, System.Windows.Forms.TreeView targetTreeView, ProjectData projectData)
        {
            int itemId = (int)readFrom;
            int fileSize = 0;
            using (Stream inStream = Utils.GetFileFromFolder(Settings.ProjectPersistenceDataItemTitle + ".zip", itemId, Settings.MigrationListTitle, out fileSize))
            {
               var progressWrapper = new ProgressStreamWrapper(inStream);

                SendProgressInit(fileSize / 1000, "Download project file from dashboard");
                progressWrapper.PositionChanged += progressWrapper_PositionChanged;

                var str = CreateUnzipStream(inStream);
                progressWrapper = new ProgressStreamWrapper(str);

                SendProgressInit(progressWrapper.Length / 1000, "Create project tree");
                progressWrapper.PositionChanged += progressWrapper_PositionChanged;

                // progressWrapper.PositionChanged += ProgressStreamPositionChanged;
                progressWrapper.Position = 0;
                LoadData(progressWrapper, sourceTreeView, targetTreeView, projectData);
            }
            SendProgressUpdateDone();
        }

        
    }
}
